package org.pine.common.beans;

import cn.hutool.cache.impl.LRUCache;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 敏感工具-加解密工具<br>
 *
 * @author pine
 * @version v1.0
 * @since 2025-04-12 13:23
 */
public class Sensitives {

    private static final LRUCache<byte[], SymmetricCrypto> CRYPTO_LRU_CACHE = new LRUCache<>(10);

    private Sensitives() {
    }

    /**
     * AES加密
     *
     * @param text 明文
     * @param key  密钥
     * @return 密文
     */
    public static String aesEncrypt(String text, byte[] key) {
        SymmetricCrypto symmetricCrypto = getAesSymmetricCrypto(key);
        // 加密为16进制表示
        return symmetricCrypto.encryptHex(text);
    }

    /**
     * AES解密
     *
     * @param text 密文
     * @param key  密钥
     * @return 明文
     */
    public static String aesDecrypt(String text, byte[] key) {
        SymmetricCrypto symmetricCrypto = getAesSymmetricCrypto(key);
        return symmetricCrypto.decryptStr(text, CharsetUtil.CHARSET_UTF_8);
    }


    /**
     * 获取AES加密解密工具
     *
     * @param key 密钥
     * @return SymmetricCrypto
     */
    public static SymmetricCrypto getAesSymmetricCrypto(byte[] key) {
        Objects.requireNonNull(key);
        SymmetricCrypto symmetricCrypto = CRYPTO_LRU_CACHE.get(key);
        if (Objects.isNull(symmetricCrypto)) {
            symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            CRYPTO_LRU_CACHE.put(key, symmetricCrypto);
        }
        return symmetricCrypto;
    }

    /**
     * 获取固定长度的key
     *
     * @param keyStr 密钥
     * @return byte[]
     */
    public static byte[] getFixedKey(String keyStr) {
        Objects.requireNonNull(keyStr);
        if (keyStr.length() < 16) {
            throw new RuntimeException("keyStr长度必须大于16");
        }
        keyStr = keyStr.substring(0, 16);
        return keyStr.getBytes(StandardCharsets.UTF_8);
    }
}
